package com.jindi.appuser.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jindi.appuser.common.*;
import com.jindi.appuser.controller.util.GetSmSCodeUtil;
import com.jindi.appuser.controller.util.HttpClientUtil;
import com.jindi.appuser.dao.*;
import com.jindi.appuser.domain.*;
import com.jindi.appuser.redis.JedisPoolUtilsJczs;
import com.jindi.appuser.service.UserService;
import com.jindi.appuser.vo.OrderVo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jindi.appplan.Conts.DRAW_CONUT_10;
import static com.jindi.appplan.Conts.DRAW_CONUT_2;

/**
 * Created with IntelliJ IDEA.
 * User: duanj
 * Date: 2017-12-21
 * Time: 14:43
 * Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private PrizeMapper prizeMapper;
    @Autowired
    private WinningRecordMapper winningRecordMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WinningListMapper winningListMapper;
    @Autowired
    private AppMapper appMapper;
    @Autowired
    private AddressMapper addressMapper;

    private static Logger logger = Logger.getLogger(HttpRequest.class.getName());
    private final static String WECHAT_USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";
    public final static String QQ_APP_ID = "101516998";
    public final static String QQ_USERINFO_URL = "https://graph.qq.com/user/get_user_info";

    @Override
    public ServerResponse checkUserName(String phone) {
        return ServerResponse.createBySuccess(userMapper.findByPhone(phone));
    }

    //检查手机号是否注册
    private boolean checkPhone(String phone) {
        return userMapper.checkPhone(phone) > 0;
    }

    /**
     * role 1--普通  2--付费
     *
     * @param phone
     * @param smsCode
     * @param pwd
     * @return
     */
    @Override
    public ServerResponse regBz(String phone, String smsCode, String pwd) {
        if (EmptyUtil.isEmpty(phone) || EmptyUtil.isEmpty(smsCode) || EmptyUtil.isEmpty(pwd)) {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        if (checkPhone(phone)) return ServerResponse.createByErrorMessage("手机号已注册");
        if (!checkSmsCode(phone, smsCode)) return ServerResponse.createByErrorMessage("验证码或手机号不正确");
        User user = new User();
        user.setCreateTime(new Date());
        user.setPhone(phone);
        user.setPwd(pwd);
        user.setRole("1");
        user.setName(phone);
        //user.setQq(EmptyUtil.toString(qq));
        //user.setCreateIp(ip);
        int index = userMapper.insertSelective(user);
        return ServerResponse.createBySuccessMessage(index > 0 ? "注册成功" : "注册失败");
    }

    User getPhoneUserInfo(String phone, String pwd, String type) {
        if (!EmptyUtil.checkParam(phone, pwd)) {
            return null;
        }
        User user = userMapper.login(phone, pwd, type);
        if (EmptyUtil.isEmpty(user)) {
            return null;
        }
        return user;
    }

    User getWeChatUserInfo(String openId, String accessToken, String type) {
        if (EmptyUtil.isEmpty(openId) || EmptyUtil.isEmpty(accessToken)) {
            return null;
        }
        if (!EmptyUtil.checkParam(openId, accessToken)) {
            return null;
        }
        User user = userMapper.findByOpenId(openId, type);
        String param = new StringBuilder("?access_token=").append(accessToken).append("&").append("openid=").append(openId).toString();
        JSONObject jsonObject = null;
        try {
            jsonObject = JSON.parseObject(HttpClientUtil.get(WECHAT_USER_INFO_URL + param.toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String imgUrl = EmptyUtil.toString(jsonObject.get("headimgurl"));
        String name = EmptyUtil.toString(jsonObject.get("nickname"));
        logger.info("wechat name" + name);
        if (EmptyUtil.isEmpty(user)) {
            if (EmptyUtil.isEmpty(imgUrl) || EmptyUtil.isEmpty(name)) {
                return null;
            }
            user = new User();
            user.setImgUrl(imgUrl);
            user.setName(name);
            Calendar cal = Calendar.getInstance();// 取当前日期。
            cal.add(Calendar.MINUTE, 60);
            user.setEndTime(cal.getTime());
            user.setRole("1");
            user.setOpenId(openId);
            user.setType(Integer.parseInt(type));
            user.setCreateTime(new Date());
            userMapper.insertSelective(user);
            return user;
        }
        user.setName(name);
        user.setImgUrl(imgUrl);
        return user;
    }


    @Override
    public ServerResponse logJczs(String phone, String pwd, String accessToken, String openId, String type) {
        User user = null;
        String username = null;
        switch (type) {
            case "0":
                user = getPhoneUserInfo(phone, pwd, type);
                if (EmptyUtil.isEmpty(user)) {
                    return ServerResponse.createByErrorMessage("登录失败，用户名或密码错误");
                }
                username = user.getPhone();
                break;
            case "1":
                user = getWeChatUserInfo(openId, accessToken, type);
                if (EmptyUtil.isEmpty(user)) {
                    return ServerResponse.createByErrorMessage("登录失败");
                }
                username = user.getName();
                break;
            case "2":
                user = getQQUserInfo(openId, accessToken, type);
                if (EmptyUtil.isEmpty(user)) {
                    return ServerResponse.createByErrorMessage("登录失败");
                }
                username = user.getName();
                break;
        }
        if (EmptyUtil.isEmpty(user)) {
            return ServerResponse.createByErrorMessage("登录失败");
        }

        Map map = new HashMap();

        if (EmptyUtil.isEmpty(user.getEndTime())) {
            Calendar cal = Calendar.getInstance();// 取当前日期。
            cal.add(Calendar.MINUTE, 60);
            user.setEndTime(cal.getTime());
            map.put("endTime", cal.getTime());
        } else if ("2".equals(user.getRole())) {
            map.put("endTime", "永久");
        } else {
            map.put("endTime", user.getEndTime());
        }
        map.put("img", EmptyUtil.toString(user.getImgUrl()));
        map.put("countDraw", EmptyUtil.toString(user.getCountDraw()));
        map.put("role", EmptyUtil.toString(user.getRole()));
        map.put("uid", EmptyUtil.toString(user.getId()));
        map.put("name", EmptyUtil.toString(username));
        return ServerResponse.createBySuccess(map);
    }


    User getQQUserInfo(String openId, String accessToken, String type) {
        if (EmptyUtil.isEmpty(accessToken) || EmptyUtil.isEmpty(openId)) {
            return null;
        }
        User user = userMapper.findByOpenId(openId, type);
        if (EmptyUtil.isEmpty(user)) {
            user = new User();
            StringBuilder param = new StringBuilder();
            param.append("?access_token=" + accessToken);
            param.append("&oauth_consumer_key=" + QQ_APP_ID);
            param.append("&openid=" + openId);
            String result = null;
            System.out.println(param.toString());
            try {

                //result = HttpRequest.sendGet(QQ_USERINFO_URL, param.toString());
                result = HttpClientUtil.get(QQ_USERINFO_URL + param.toString());

            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONObject json = JSON.parseObject(result);

            //   User user1 = new User();
            String nickname = (String) json.get("nickname");
            String userImg = (String) json.get("figureurl");
            logger.info("qq name" + nickname);
            if (!EmptyUtil.isEmpty(nickname) && !EmptyUtil.isEmpty(userImg)) {
                user.setName(nickname);
                user.setImgUrl(userImg);
            }
            user.setRole("1");
            user.setOpenId(openId);
            user.setType(Integer.parseInt(type));
            Calendar cal = Calendar.getInstance();// 取当前日期。
            cal.add(Calendar.MINUTE, 60);
            user.setEndTime(cal.getTime());
            user.setCreateTime(new Date());
            userMapper.insertSelective(user);
            logger.info("qq getName" + user.getName());
            return user;
        }
        return user;
    }

    @Override
    public ServerResponse restPwdJczs(String phone, String smsCode, String newPwd) {
        if (!EmptyUtil.checkParam(phone, smsCode, newPwd)) {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        User user = userMapper.findByPhone(phone);
        if (EmptyUtil.isEmpty(user)) return ServerResponse.createByErrorMessage("手机号未注册");
        //校验手机号，和验证码
        if (!checkSmsCode(phone, smsCode)) return ServerResponse.createByErrorMessage("验证码或手机号不正确");
        user.setPwd(newPwd);
        int index = userMapper.updateByPrimaryKeySelective(user);
        if (index > 0) {
            return ServerResponse.createBySuccessMessage("密码修改成功");
        }
        return ServerResponse.createBySuccessMessage("密码修改失败");
    }


    public static void main(String[] args) {
        String strDate="2019-3-25 4:00:00";
        //注意：SimpleDateFormat构造函数的样式与strDate的样式必须相符
        SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //加上时间
        //必须捕获异常
        try {
            Date date=sDateFormat.parse(strDate);
            System.out.println(date);
        } catch(ParseException px) {
            px.printStackTrace();
        }
    }

    /**
     * TODO 除法运算，保留小数
     *
     * @param a 被除数
     * @param b 除数
     * @return 商
     * @author 袁忠明
     * @date 2018-4-17下午2:24:48
     */
    public static String txfloat(int a, int b) {
        // TODO 自动生成的方法存根

        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数

        return df.format((float) a / b);

    }


    @Override
    public ServerResponse luckDraw(String uid) {
        appMapper.selectByPrimaryKey(1);
        if (!"1".equals(appMapper.selectByPrimaryKey(1).getDrowStatus())) {
            return ServerResponse.createByErrorMessage("活动已结束");
        }

        User user = userMapper.selectByPrimaryKey(Integer.parseInt(uid));

        if (EmptyUtil.isEmpty(user)) {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        if (Integer.parseInt(user.getCountDraw()) < 1) {
            return ServerResponse.createByErrorMessage("抽奖次数用完啦，请明天再来");
        }
        List<Prize> list = prizeMapper.listAll();
        int max = 200;
        int min = 1;
        int a = 0;
        int b = (int) (Math.random() * (max - min)) + min;

        if ("2".equals(user.getRole())) {
            if (b == 1) {
                a = 5;
            } else if (b > 1 && b <= 8) {
                a = 7;
            } else if (b > 8 && b <= 12) {
                a = 4;
            } else if (b > 12 && b <= 22) {
                a = 3;
            } else if (b > 22 && b <= 25) {
                a = 6;
            } else if (b > 25) {
                a = 2;
            }
        } else {
            if (b < 20) {
                a = 1;
            } else if (b >= 21 && b <= 25) {
                a = 6;
            } else if (b > 25) {
                a = 2;
            }
        }


        //购买过的用户第一次必中10元
        if ("2".equals(user.getFirstPay())) {
            a = 1;
        }

        //添加中奖记录

        //设置次数 a=6 再来一次
        if (a != 6) {
            user.setCountDraw(EmptyUtil.toString(Integer.parseInt(user.getCountDraw()) - 1));
            if (list.get(a - 1).getStatus() == 0) {
                addWinningRecord(user, a, list.get(a - 1).getName());
            }
        }

        Map map = new HashMap();
        map.put("num", a);
        map.put("name", list.get(a - 1).getName());
        map.put("count", user.getCountDraw());
        user.setFirstPay("1");
        userMapper.updateByPrimaryKeySelective(user);
        return ServerResponse.createBySuccess(map);
    }

    @Override
    public ServerResponse makeList() {
        List<Prize> listPize = prizeMapper.listAll();
        List<WinningList> list = winningListMapper.listAll();
        for (WinningList winningList : list) {
            int max = 200;
            int min = 1;
            int a = 0;
            int b = (int) (Math.random() * (max - min)) + min;

            if (b == 1) {
                a = 8;
            } else if (b > 1 && b <= 8) {
                a = 5;
            } else if (b > 8 && b <= 12) {
                a = 7;
            } else if (b > 12 && b <= 22) {
                a = 4;
            } else if (b > 22 && b <= 25) {
                a = 3;
            } else if (b > 25) {
                a = 1;
            }
            if (a == 2) {
                a = 1;
            }
            if (a == 6) {
                a = 1;
            }
            winningList.setPrizeName(listPize.get(a - 1).getName());
            winningListMapper.updateByPrimaryKeySelective(winningList);
        }
        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse getMyPrizeList(String uid) {
        List<WinningRecord> list1 = winningRecordMapper.listByUid(Integer.parseInt(uid));
        if (list1.size() < 1) {
            return ServerResponse.createByErrorMessage("您还没抽中任何奖品");
        }
        return ServerResponse.createBySuccess(list1);
    }

    @Override
    public ServerResponse winningRecordUpdate(String doType,String wid) {
       if( EmptyUtil.isEmpty(doType)|| EmptyUtil.isEmpty(wid)){
           return ServerResponse.createByErrorMessage("参数错误");
       }
        WinningRecord winningRecord = winningRecordMapper.selectByPrimaryKey(Integer.parseInt(wid));
        if(doType.equals("1")){//  1，处理完成   0，处理中
           winningRecord.setPrizeStatus("处理完成");
       }else if(doType.equals("0")){
            winningRecord.setPrizeStatus("处理中");
       }
        Integer index = winningRecordMapper.updateByPrimaryKeySelective(winningRecord);
       if(index>0){
           return ServerResponse.createBySuccess("处理成功");
       }
        return ServerResponse.createByErrorMessage("处理失败");
    }

    @Override
    public ServerResponse winningRecordInfo(String id) {
        if(EmptyUtil.isEmpty(id)){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        WinningRecord winningRecord = winningRecordMapper.selectByPrimaryKey(Integer.parseInt(id));
        if(EmptyUtil.isEmpty(winningRecord)){
            return ServerResponse.createByErrorMessage("什么都没有查到");
        }
        return ServerResponse.createBySuccess(winningRecord);
    }

    @Override
    public ServerResponse userUpdate(String uid, String count) {
        if(EmptyUtil.isEmpty(uid) || EmptyUtil.isEmpty(count)){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        User user = userMapper.selectByPrimaryKey(Integer.parseInt(uid));
        user.setCountDraw(EmptyUtil.toString(Integer.parseInt(user.getCountDraw())+Integer.parseInt(count)));
        Integer integer = userMapper.updateByPrimaryKeySelective(user);
        if(integer>0)return ServerResponse.createBySuccess("修改成功");
        return ServerResponse.createByErrorMessage("修改失败");
    }

    @Override
    public ServerResponse delUser(String uid) {
        Integer integer = userMapper.deleteByPrimaryKey(Integer.parseInt(uid));
        if(integer>0){
            return ServerResponse.createBySuccess("封禁成功");
        }
        return ServerResponse.createByErrorMessage("封禁失败");
    }

    @Override
    public ServerResponse userAddressList(String uid) {
        List<Address> list = addressMapper.queryAddressListByUid(Integer.parseInt(uid));
        if(list.size()>0)return ServerResponse.createBySuccess(list);
        return ServerResponse.createByErrorMessage("暂无数据");
    }

    @Override
    public ServerResponse updateUserTimeByAid(String uid) {
        return null;
    }

    public static  Date  makeTime(String time){
        //注意：SimpleDateFormat构造函数的样式与strDate的样式必须相符
        SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //加上时间
        //必须捕获异常
        try {
          Date date=sDateFormat.parse(time);
          return date;
        } catch(ParseException px) {
          px.printStackTrace();
        }
        return null;
    }


    @Override
    public ServerResponse userUpdateTime(String uid, String time) {
        if(EmptyUtil.isEmpty(uid) || EmptyUtil.isEmpty(time)){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        User user = userMapper.selectByPrimaryKey(Integer.parseInt(uid));
        user.setEndTime(makeTime(time));
        user.setRole("2");
        Integer integer = userMapper.updateByPrimaryKeySelective(user);
        if(integer>0)return ServerResponse.createBySuccess("修改成功");
        return ServerResponse.createByErrorMessage("修改失败");
    }

    /**
     * @param user
     * @param num  对应前端抽奖圆盘num
     */
    void addWinningRecord(User user, int num, String prizeName) {
        WinningRecord winningRecord = new WinningRecord();
        winningRecord.setCreateTime(new Date());
        winningRecord.setPrizeId(num);
        winningRecord.setUid(user.getId());
        winningRecord.setUphone(user.getPhone() == null ? user.getName() : user.getPhone());
        winningRecord.setPrizeName(prizeName);
        winningRecord.setPrizeStatus("处理中");
        winningRecordMapper.insertSelective(winningRecord);
    }


    @Override
    public ServerResponse luckDrawInit(String uid) {
        User user = userMapper.selectByPrimaryKey(Integer.parseInt(uid));
        if (EmptyUtil.isEmpty(user)) {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        List<WinningList> list = winningListMapper.list();
        // List<WinningRecord> list1 = winningRecordMapper.listByUid(Integer.parseInt(uid));
        Map map = new HashMap();
        for (WinningList winningList : list) {
            if (winningList.getUphone().length() > 3) {
                //winningList.setUphone(winningList.getUphone().split());
                if (winningList.getUphone().length() > 5) {
                    winningList.setUphone(winningList.getUphone().substring(0, 3) + "******" + winningList.getUphone().substring(winningList.getUphone().length() - 2, winningList.getUphone().length()));
                } else {
                    winningList.setUphone(winningList.getUphone());
                }
            }
        }
        // map.put("myPrize", list1);
        map.put("allPrize", list);
        map.put("url", "https://img.jindi163.com/icons/yys@3x.png");
        map.put("count", user.getCountDraw());
        return ServerResponse.createBySuccess(map);
    }

    @Override
    public ServerResponse signIn(String uid) {
        return null;
    }

    @Override
    public ServerResponse checkPower(String uid) {
        if (EmptyUtil.isEmpty(uid)) {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        User user = userMapper.selectByPrimaryKey(Integer.parseInt(uid));
        if (EmptyUtil.isEmpty(user)) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String power_play = "0";
        String power_setting = "0";
        if ("2".equals(user.getRole())) {
            power_setting = "1";
            power_play = "1";
        } else if ("1".equals(user.getRole()) && user.getEndTime().getTime() > new Date().getTime()) {
            power_play = "1";
            power_setting = "0";
        } else {
            power_play = "0";
            power_setting = "0";
        }
        Map map = new HashMap();
        map.put("power_play", power_play);
        map.put("power_setting", power_setting);
        map.put("count", user.getCountDraw());
        map.put("role", user.getRole());
        map.put("img", user.getImgUrl());
        map.put("name", user.getPhone() == null ? user.getName() : user.getPhone());
        map.put("endTime", user.getEndTime());
        return ServerResponse.createBySuccess(map);
    }

    @Override
    public ServerResponse getUserInfo(String uid) {
        User user = userMapper.selectByPrimaryKey(Integer.parseInt(uid));
        return ServerResponse.createBySuccess(user);
    }

    @Override
    public ServerResponse sign(String uid) {
        if (EmptyUtil.isEmpty(uid)) {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        User user = userMapper.selectByPrimaryKey(Integer.parseInt(uid));
        if (EmptyUtil.isEmpty(user)) {
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        if (!EmptyUtil.isEmpty(user.getIsSign()) && user.getIsSign() == 1) {
            return ServerResponse.createByErrorMessage("你今天已经签到了");
        }
        user.setIsSign(1);
        user.setCountDraw(String.valueOf(Integer.parseInt(user.getCountDraw()) + 1));
        userMapper.updateByPrimaryKeySelective(user);
        return ServerResponse.createBySuccess("签到成功");
    }

    @Override
    public ServerResponse userList(String name, String pageNum, String pageSize) {
        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        List<User> list = userMapper.listUser("%" + name + "%");
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse orderList(String name, String pageNum, String pageSize) {
        if (EmptyUtil.isEmpty(name)) {
            PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
            List<Order> list = orderMapper.listOrder(null);
            PageInfo pageInfo = new PageInfo(list);
            return ServerResponse.createBySuccess(pageInfo);
        }
        User user = userMapper.checkUserByName(name);
        if (EmptyUtil.isEmpty(user)) {
            return ServerResponse.createByErrorMessage("暂无数据");
        }
        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        List<Order> list = orderMapper.listOrder(user.getId().toString());
        for (Order order : list) {

        }
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse orderListName(String name, String pageNum, String pageSize) {
        if (EmptyUtil.isEmpty(name)) {
            PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
            List<OrderVo> list = orderMapper.listOrderName(null);
            PageInfo pageInfo = new PageInfo(list);
            return ServerResponse.createBySuccess(pageInfo);
        }
        User user = userMapper.checkUserByName(name);
        if (EmptyUtil.isEmpty(user)) {
            return ServerResponse.createByErrorMessage("暂无数据");
        }
        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        List<OrderVo> list = orderMapper.listOrderName(user.getId().toString());
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse queryAddressDetailsByAid(String aid) {
        Address address = addressMapper.selectByPrimaryKey(Integer.parseInt(aid));
        if (!EmptyUtil.isEmpty(address)) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", EmptyUtil.toString(address.getName()));
            jsonObject.put("phone", EmptyUtil.toString(address.getPhone()));
            jsonObject.put("address", EmptyUtil.toString(address.getAddress()));
            jsonObject.put("aid", EmptyUtil.toString(address.getId()));
            jsonObject.put("type", EmptyUtil.toString(address.getType()));
            return ServerResponse.createBySuccess(jsonObject);
        }
        return ServerResponse.createByErrorMessage("查询失败");
    }

    @Override
    public ServerResponse queryAddressListByUid(String uid) {
        List<Address> addressList = addressMapper.queryAddressListByUid(Integer.parseInt(uid));
        List<JSONObject> jsonObjectList = new LinkedList<>();
        if (addressList != null && addressList.size() > 0) {
            for (Address address : addressList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("name", EmptyUtil.toString(address.getName()));
                jsonObject.put("phone", EmptyUtil.toString(address.getPhone()));
                jsonObject.put("address", EmptyUtil.toString(address.getAddress()));
                jsonObject.put("aid", EmptyUtil.toString(address.getId()));
                jsonObject.put("type", EmptyUtil.toString(address.getType()));
                jsonObjectList.add(jsonObject);
            }

        }
        if (jsonObjectList.size() > 0) {
            return ServerResponse.createBySuccess(jsonObjectList);
        }
        return ServerResponse.createByErrorMessage("当前无收货地址记录");
    }

    @Override
    public ServerResponse delAddressByAid(String aid) {
        int index = addressMapper.deleteByPrimaryKey(Integer.parseInt(aid));
        if (index > 0) {
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("删除失败");
    }

    @Override
    public ServerResponse addAddress4User(Address address) {
        if (EmptyUtil.isEmpty(address.getId())) {
            int index = addressMapper.insertSelective(address);
            if (index > 0) {
                return ServerResponse.createBySuccessMessage("添加成功");
            }
        } else {
            int index = addressMapper.updateByPrimaryKeySelective(address);
            if (index > 0) {
                return ServerResponse.createBySuccessMessage("修改成功");
            }
        }
        return ServerResponse.createByErrorMessage("添加错误");
    }

    @Override
    public ServerResponse getSmsCode(String phone, String ip, String type) {
        if (EmptyUtil.isEmpty(phone)) {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        if (phone.length() != 11 || !phone.startsWith("1")) {
            return ServerResponse.createByErrorMessage("请输入正确的手机号");
        }

        //检查手机号是否注册
        if ("1".equals(type)) {
            if (checkPhone(phone)) {
                return ServerResponse.createByErrorMessage("手机号已注册请登录");
            }
        } else {
            if (!checkPhone(phone)) {
                return ServerResponse.createByErrorMessage("手机号未注册，请检查");
            }
        }

        Jedis jedis = JedisPoolUtilsJczs.getJedis();
        try {
            //校验手机号能否发送验证码
            String phoneCount = jedis.hget(YYS_SMS_COUNT, phone);
            if (!EmptyUtil.isEmpty(phoneCount) && Integer.parseInt(phoneCount) > 5) {
                return ServerResponse.createByErrorMessage("次数到上限");
            }
            //防止同一IP多次发送无意义验证码
            //  String ipCount = jedis.hget(BZ_JCZS_IP_COUNT,appId+phone);
            if (jedis.exists(ip) && jedis.hgetAll(ip).keySet().size() > 10) {
                return ServerResponse.createByErrorMessage("此IP已受限，请谨慎操作");
            }
            String code = GetSmSCodeUtil.getRandom();
            if ("0".equals(GetSmSCodeUtil.getCode(phone, code))) {
                jedis.set(phone, code);
                jedis.expire(phone, 60 * 5);
                jedis.hset(ip, phone, code);
                jedis.expire(ip, 60 * 5);
                jedis.hset(YYS_SMS_COUNT, phone, EmptyUtil.toString(Integer.parseInt(phoneCount == null ? "0" : phoneCount) + 1));
                jedis.expire(YYS_SMS_COUNT, (int) TimeUtils.getTimeToTomorow());
                return ServerResponse.createBySuccessMessage("验证码发送成功");
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            JedisPoolUtilsJczs.returnBrokenResource(jedis);
        } finally {
            JedisPoolUtilsJczs.returnJedis(jedis);
        }
        //发送验证码
        return ServerResponse.createByErrorMessage("验证码发送失败");
    }

    public static final String YYS_SMS_COUNT = "yys_sms_count";

    //校验验证码
    boolean checkSmsCode(String phone, String smsCode) {
        Jedis jedis = JedisPoolUtilsJczs.getJedis();
        try {
            if (jedis.exists(phone) && EmptyUtil.toString(jedis.get(phone)).equals(smsCode)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            JedisPoolUtilsJczs.returnBrokenResource(jedis);
        } finally {
            JedisPoolUtilsJczs.returnJedis(jedis);
        }
        return false;
    }

    public ServerResponse countOrder() {
        Map<String, Object> map = new HashMap<String, Object>();
        Double yestday = 0.00;
        Double today = 0.00;
        Double thisWeek = 0.00;
        Double lastWeek = 0.00;
        Double thisMonth = 0.00;
        Double lastMonth = 0.00;
        Double thisYear = 0.00;
        Double lastYear = 0.00;
        String startTime = DateUtil.getYestoday().get("startTime");
        String endTime = DateUtil.getYestoday().get("endTime");
        yestday = orderMapper.getAllOrderCount(startTime, endTime);
        today = orderMapper.getAllOrderCount(DateUtil.getToday().get("startTime"), DateUtil.getToday().get("endTime"));
        thisWeek = orderMapper.getAllOrderCount(DateUtil.getThisWeek().get("startTime"), DateUtil.getThisWeek().get("endTime"));
        lastWeek = orderMapper.getAllOrderCount(DateUtil.getLastWeek().get("startTime"), DateUtil.getLastWeek().get("endTime"));
        thisMonth = orderMapper.getAllOrderCount(DateUtil.getMonth().get("thisMonthStart"), DateUtil.getMonth().get("thisMonthEnd"));
        lastMonth = orderMapper.getAllOrderCount(DateUtil.getMonth().get("lastMonthStart"), DateUtil.getMonth().get("lastMonthEnd"));
        //int allCount = codeMapper.getCountAll();
        Calendar currCal = Calendar.getInstance();
        Integer currentYear = currCal.get(Calendar.YEAR);
        thisYear = orderMapper.getAllOrderCount(DateUtil.formatDate(DateUtil.getYearFirst(currentYear)) + "000000", DateUtil.formatDate(DateUtil.getYearLast(currentYear)) + "235959");
        lastYear = orderMapper.getAllOrderCount(DateUtil.formatDate(DateUtil.getYearFirst(currentYear - 1)) + "000000", DateUtil.formatDate(DateUtil.getYearLast(currentYear - 1)) + "235959");

        map.put("yestday", yestday == null ? 0.00 : yestday);
        map.put("today", today == null ? 0.00 : today);
        map.put("thisWeek", thisWeek == null ? 0.00 : thisWeek);
        map.put("lastWeek", lastWeek == null ? 0.00 : lastWeek);
        map.put("thisMonth", thisMonth == null ? 0.00 : thisMonth);
        map.put("lastMonth", lastMonth == null ? 0.00 : lastMonth);
        map.put("thisYear", thisYear == null ? 0.00 : thisYear);
        map.put("lastYear", lastYear == null ? 0.00 : lastYear);
        return ServerResponse.createBySuccess(map);
    }

    public ServerResponse countOrderNum() {
        Map<String, Object> map = new HashMap<String, Object>();
        Integer yestday = 0;
        Integer today = 0;
        Integer thisWeek = 0;
        Integer lastWeek = 0;
        Integer thisMonth = 0;
        Integer lastMonth = 0;
        Integer thisYear = 0;
        Integer lastYear = 0;
        String startTime = DateUtil.getYestoday().get("startTime");
        String endTime = DateUtil.getYestoday().get("endTime");
        yestday = orderMapper.getAllOrderCountNum(startTime, endTime);
        today = orderMapper.getAllOrderCountNum(DateUtil.getToday().get("startTime"), DateUtil.getToday().get("endTime"));
        thisWeek = orderMapper.getAllOrderCountNum(DateUtil.getThisWeek().get("startTime"), DateUtil.getThisWeek().get("endTime"));
        lastWeek = orderMapper.getAllOrderCountNum(DateUtil.getLastWeek().get("startTime"), DateUtil.getLastWeek().get("endTime"));
        thisMonth = orderMapper.getAllOrderCountNum(DateUtil.getMonth().get("thisMonthStart"), DateUtil.getMonth().get("thisMonthEnd"));
        lastMonth = orderMapper.getAllOrderCountNum(DateUtil.getMonth().get("lastMonthStart"), DateUtil.getMonth().get("lastMonthEnd"));
        //int allCount = codeMapper.getCountAll();
        Calendar currCal = Calendar.getInstance();
        Integer currentYear = currCal.get(Calendar.YEAR);
        thisYear = orderMapper.getAllOrderCountNum(DateUtil.formatDate(DateUtil.getYearFirst(currentYear)) + "000000", DateUtil.formatDate(DateUtil.getYearLast(currentYear)) + "235959");
        lastYear = orderMapper.getAllOrderCountNum(DateUtil.formatDate(DateUtil.getYearFirst(currentYear - 1)) + "000000", DateUtil.formatDate(DateUtil.getYearLast(currentYear - 1)) + "235959");

        map.put("yestday", yestday == null ? 0 : yestday);
        map.put("today", today == null ? 0 : today);
        map.put("thisWeek", thisWeek == null ? 0 : thisWeek);
        map.put("lastWeek", lastWeek == null ? 0 : lastWeek);
        map.put("thisMonth", thisMonth == null ? 0 : thisMonth);
        map.put("lastMonth", lastMonth == null ? 0 : lastMonth);
        map.put("thisYear", thisYear == null ? 0 : thisYear);
        map.put("lastYear", lastYear == null ? 0 : lastYear);
        return ServerResponse.createBySuccess(map);
    }

    @Override
    public ServerResponse countUserList() {
        String startTime = DateUtil.getYestoday().get("startTime");
        String endTime = DateUtil.getYestoday().get("endTime");
        List list = new ArrayList();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("yestday", userMapper.getUserCount(startTime, endTime));
        map.put("today", userMapper.getUserCount(DateUtil.getToday().get("startTime"), DateUtil.getToday().get("endTime")));
        map.put("thisWeek", userMapper.getUserCount(DateUtil.getThisWeek().get("startTime"), DateUtil.getThisWeek().get("endTime")));
        map.put("lastWeek", userMapper.getUserCount(DateUtil.getLastWeek().get("startTime"), DateUtil.getLastWeek().get("endTime")));
        map.put("thisMonth", userMapper.getUserCount(DateUtil.getMonth().get("thisMonthStart"), DateUtil.getMonth().get("thisMonthEnd")));
        map.put("lastMonth", userMapper.getUserCount(DateUtil.getMonth().get("lastMonthStart"), DateUtil.getMonth().get("lastMonthEnd")));
        map.put("allCount", userMapper.getUserCountAll());
        list.add(map);
        return ServerResponse.createBySuccess(list);
    }

    @Override
    public ServerResponse winningRecordList(String name, Integer pageSize , Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        List<WinningRecord> list = winningRecordMapper.winningRecordList(name);
        if (list.size() < 1) {
            return ServerResponse.createByErrorMessage("暂无数据");
        }
        PageInfo pageInfo = new PageInfo(list);
        return ServerResponse.createBySuccess(pageInfo);
    }
}
